import time
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class Burger(BaseBrush):
    login_url = "http://xhb_shop.daee10.cn/user/login.html"
    index_url = "http://xhb_shop.daee10.cn/member/Sellerindex"
    check_url = "http://xhb_shop.daee10.cn/member/auditBuyerAccount/index"

    def __init__(self, config, tab):
        super().__init__("小汉堡", "burger", config, tab)

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.ID, "j_username"), self.username)
        self.enter_text((By.ID, "j_password"), self.password)
        self.click_button((By.ID, "login"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        try:
            trs = self.find_elements((By.CSS_SELECTOR, "tbody>tr"), timeout=5)
        except Exception as e:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        tr = trs[0]
        tds = tr.find_elements_by_tag_name("td")

        username = tds[-3].get_attribute('textContent').strip()
        username = username.replace("验号信息", "").strip()
        self.print_log(f"当前待验买号为：【{username}】")

        start = time.time()
        result = self.check.check_user(username, self.print_log)
        self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

        if not result:
            button_idx = -1
        else:
            button_idx = -2

        button = tds[button_idx].find_element_by_tag_name("input")
        click_by_js(self.browser, button)
        # 点击确认
        self.click_button((By.CSS_SELECTOR, "a.layui-layer-btn0"))

        if len(trs) == 1:
            self.sleep(self.refresh_time)
        else:
            self.sleep(2)
        return False
